package Form;

use strict;
use CGI qw(:standard);
use @@PACKAGE@@::WebAPI::Util;

sub new {

    # Get the class name
    my $stInvocant = shift @_;
    my $stClass = ref($stInvocant) || $stInvocant;

    # Create the current instance and bless into class
    my $rSelf = { };
    bless($rSelf,$stClass);

    # All arguments are treated as the table attr
    # default attr are driven by the display (i.e., browser)
    my %hFormAttr = ( @_ );
    $rSelf->{form_attr} = \%hFormAttr;
    $rSelf->{hidden_fields} = {};

    $rSelf->{children} = [];
    $rSelf->{num_children} = 0;

    return $rSelf;
}

sub addChild {

    my $rSelf = shift(@_);
    my $rChild = shift(@_);
    
    if ( defined($rChild) ) {

	$rSelf->{children}->[$rSelf->{num_children}] = $rChild;
	$rSelf->{num_children}++;

    }
    
    return 1;
}

sub addHiddenFields {

    my $rSelf= shift(@_);
    my $rhHiddenFields = shift(@_);
    my $stKey;
    foreach $stKey (keys %$rhHiddenFields) {

	$rSelf->{hidden_fields}->{$stKey} = $rhHiddenFields->{$stKey};
    }
}

sub draw {

    my $rSelf = shift(@_);
    my $stResult = "";

    $stResult = "<form".Util::get_attr_str($rSelf->{form_attr}).">\n";

    my $i = 0;    
    for $i (0 .. $rSelf->{num_children}-1) {

	if ( defined( $rSelf->{children}->[$i] ) ) {

	    $stResult .= 
		ref( $rSelf->{children}->[$i] ) ?
		$rSelf->{children}->[$i]->draw() :
		$rSelf->{children}->[$i];
	}
    }

    my $rhHiddenFields = $rSelf->{hidden_fields};
    my $stKey;
    foreach $stKey (keys %$rhHiddenFields) {

	$stResult .= hidden(-name=>$stKey,-value=>$rhHiddenFields->{$stKey},-override=>1)."\n";
    }

    
    $stResult .= "</form>\n";

    return $stResult;
}

1;
